package com.nttuan.mycalender;

import android.app.Activity;
import android.app.Dialog;
import android.content.DialogInterface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;
import android.widget.ToggleButton;

import com.nttuan.adapter.FindUserAdapter;
import com.nttuan.flows.ContactListener;
import com.nttuan.model.dao.LocationDao;
import com.nttuan.model.dao.TrackDao;
import com.nttuan.model.dao.service.LocationService;
import com.nttuan.model.dao.service.TrackService;
import com.nttuan.model.entity.Track;
import com.nttuan.adapter.ConflictAdapter;
import com.nttuan.adapter.ContactDetailAdapter;
import com.nttuan.adapter.SysContactAdapter;
import com.nttuan.flows.MultiSelectListener;
import com.nttuan.model.dao.ContactDao;
import com.nttuan.model.dao.TaskDao;
import com.nttuan.model.dao.UserDao;
import com.nttuan.model.dao.service.ContactService;
import com.nttuan.model.dao.service.TaskService;
import com.nttuan.model.dao.service.UserService;
import com.nttuan.model.entity.Category;
import com.nttuan.model.entity.Clash;
import com.nttuan.model.entity.Contact;
import com.nttuan.model.entity.Task;
import com.nttuan.model.entity.User;
import com.nttuan.util.ContactSupport;
import com.nttuan.util.JSONParser;
import com.nttuan.util.LogSupport;
import com.nttuan.util.Network;
import com.nttuan.util.SysApp;
import com.nttuan.util.Support;
import com.nttuan.view.MultiSelect;
import com.nttuan.view.SelectView;
import com.nttuan.view.SlideEditText;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * Created by NT Tuan on 10/25/2014.
 */
public class AddNewActivity extends Activity implements View.OnClickListener, AdapterView.OnItemClickListener
        , TextWatcher, MultiSelectListener, DialogInterface.OnCancelListener, ContactListener{

    private static final String sLastDate = "1/1/2090";
    public static String KEY_BUNDLE = "myBundle";
    public static String KEY_ACTION = "action";
    public static String KEY_TASK_ID = "taskId";

    public static final int KEY_ACTION_ADD = 1;
    public static final int KEY_ACTION_ADD_FREE = 2;
    public static final int KEY_ACTION_VIEW = 3;
    public static final int KEY_ACTION_VIEW_INVITE = 4;

    private boolean isSetEndDate = false;
    private boolean isInvite = false;
    private boolean isCreate = true;
    private boolean isUpdateInfoInvite;
    private String message = "";

    private ProgressBar progressBar;
    private ToggleButton btnInvite;
    //    private ScrollView scrollView;
    private MultiSelect multiRepeat;
    private TextView textDateStart;
    private TextView textDateEnd;
    private TextView textTimeStart;
    private TextView textTimeEnd;
    private TextView textAction;

    private LinearLayout layoutActionDefault;
    private LinearLayout layoutActionEdit;
    private SelectView selectAlarm;
    private SlideEditText slideAlarm;
    private EditText txtTaskName;
    private EditText txtSearchContact;
    private AutoCompleteTextView txtLocation;
    private EditText txtNote;
    private GridView listViewContact;
    private ListView listViewSysContact;
    private ImageButton iBtnBack;
    private ImageButton iBtnCancel;
    private ImageButton iBtnSave;
    private ImageButton iBtnEdit;
    private ImageButton iBtnDelete;
    private ImageButton iBtnSearch;
    private ImageButton iBtnSendMail;
    private ToggleButton toggleAttend;

    private ArrayAdapter<String> locationAdapter;
    private SysContactAdapter sysContactAdapter;
    private ContactDetailAdapter contactAdapter;
    private List<User> listUser = new ArrayList<User>();
    private TaskService taskService;
    private ContactService contactService;
    private UserService userService;
    private LocationService locationService;
    private saveTask loadSaveTask;


    private Task currentTask;

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_new2);
        initView();
        initAction();
//        action add new, edit, view ...
        action();
        enableEndDate(multiRepeat.getData());

//        test

    }

    private void initView() {
        progressBar = (ProgressBar) findViewById(R.id.progressBar);
        btnInvite = (ToggleButton) findViewById(R.id.iBtnInviteAddNew);

        multiRepeat = (MultiSelect) findViewById(R.id.mutilSelectRepeat);
        textDateStart = (TextView) findViewById(R.id.textStartAddNew);
        textDateEnd = (TextView) findViewById(R.id.textEndAddNew);
        textTimeStart = (TextView) findViewById(R.id.textStartTimeAddNew);
        textTimeEnd = (TextView) findViewById(R.id.textEndTimeAddNew);
        textAction = (TextView) findViewById(R.id.textActionAddNew);

        listViewContact = (GridView) findViewById(R.id.listViewContactAddNew);
        listViewSysContact = (ListView) findViewById(R.id.listViewSysContactAddNew);
        layoutActionDefault = (LinearLayout) findViewById(R.id.lLayoutDefaultAddNew);
        layoutActionEdit = (LinearLayout) findViewById(R.id.lLayoutEditAddNew);
        selectAlarm = (SelectView) findViewById(R.id.selectViewAlarm);

        slideAlarm = (SlideEditText) findViewById(R.id.slideTextAlarm);
        txtTaskName = (EditText) findViewById(R.id.txtNameDetail);
        txtSearchContact = (EditText) findViewById(R.id.txtSearchContact);
        txtLocation = (AutoCompleteTextView) findViewById(R.id.txtLocationDetail);
        txtNote = (EditText) findViewById(R.id.txtNoteDetail);
        iBtnBack = (ImageButton) findViewById(R.id.iBtnBackAđNew);
        iBtnCancel = (ImageButton) findViewById(R.id.iBtnCancelAddNew);
        iBtnSave = (ImageButton) findViewById(R.id.iBtnSaveAddNew);
        iBtnEdit = (ImageButton) findViewById(R.id.iBtnEditAddNew);
        iBtnDelete = (ImageButton) findViewById(R.id.iBtnDeleteAddNew);
        iBtnSearch = (ImageButton) findViewById(R.id.iBtnSearchUser);
        iBtnSendMail = (ImageButton) findViewById(R.id.iBtnSendMail);
        toggleAttend = (ToggleButton) findViewById(R.id.toggleAttendAddNew);
    }

    private void initAction() {
        currentTask = new Task();
        multiRepeat.setListener(this);
        btnInvite.setOnClickListener(this);
        txtSearchContact.addTextChangedListener(this);

        taskService = TaskDao.getInstance(this);
        contactService = ContactDao.getInstance(this);
        locationService = LocationDao.getInstance(this);
        userService = UserDao.getInstance(this);
        textDateStart.setOnClickListener(this);
        textTimeStart.setOnClickListener(this);
        textDateEnd.setOnClickListener(this);
        textTimeEnd.setOnClickListener(this);
        iBtnBack.setOnClickListener(this);
        iBtnCancel.setOnClickListener(this);
        iBtnSave.setOnClickListener(this);
        iBtnEdit.setOnClickListener(this);
        iBtnDelete.setOnClickListener(this);
        iBtnSearch.setOnClickListener(this);
        iBtnSendMail.setOnClickListener(this);
        toggleAttend.setOnClickListener(this);

        contactAdapter = new ContactDetailAdapter(this, currentTask.getListContact(), userService.getMe());
        contactAdapter.setListener(this);
        listViewContact.setAdapter(contactAdapter);
        listViewContact.setOnItemClickListener(contactClick);

        sysContactAdapter = new SysContactAdapter(this, listUser, currentTask.getListContact());
        listViewSysContact.setAdapter(sysContactAdapter);
        listViewSysContact.setOnItemClickListener(this);

//        auto complete
        locationAdapter = new ArrayAdapter<String>(this, R.layout.item_drop_down, locationService.listAddress());
        txtLocation.setAdapter(locationAdapter);

        loadSaveTask = new saveTask();
    }

    private void action() {
        Bundle bundle = getIntent().getBundleExtra(KEY_BUNDLE);
        int action = bundle.getInt(KEY_ACTION);
        switch (action) {
            case KEY_ACTION_ADD:
                isCreate = true;
                isInvite = false;
                textAction.setText(R.string.action_add_new);
                showEditBar(true);
                setCurrentDate();
                break;
            case KEY_ACTION_ADD_FREE:
                isCreate = true;
                isInvite = false;
                Date from = Support.toDateTime(bundle.getString(Task.DATE_START), false);
                int during = bundle.getInt(Task.DURING);
                updateUiFromFreeTime(from, during);
                showEditBar(true);
                break;
            case KEY_ACTION_VIEW:
                isCreate = false;
                isInvite = false;
                int taskId = bundle.getInt(KEY_TASK_ID);
                new loadCurrentTask(taskId).execute();
                enableEditor(false);
                break;
            case KEY_ACTION_VIEW_INVITE:
                isCreate = false;
                isInvite = true;
                int id = bundle.getInt(KEY_TASK_ID);
                new loadCurrentTask(id).execute();

                break;
        }
    }

    private Contact getContactMe() {
        Contact me = new Contact();
        me.setUser(userService.getMe());
        me.setContactId(0);
        me.setLeader(true);
        me.setActive(true);
        me.setAttend(true);
        return me;
    }

    private void deleteTask(final int taskId) {
        final Dialog dialog = new Dialog(this);
        View view = LayoutInflater.from(this).inflate(R.layout.dialog_confirm, null);
        dialog.setContentView(view);
        Button btnOk = (Button) view.findViewById(R.id.btnOkConfirmDialog);
        Button btnCancel = (Button) view.findViewById(R.id.btnCancelConfirmDialog);
        btnOk.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (taskService.active(taskId,false)) {
//                    MainReceiver.alarmService.update(); --------------------------------------------update log here
                    LogSupport.saveLog(AddNewActivity.this, taskService.getAlarm(Calendar.getInstance().getTime()));
                    finish();
                } else
                    Toast.makeText(getBaseContext(), R.string.delete_error, Toast.LENGTH_SHORT).show();
                dialog.dismiss();
            }
        });
        btnCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();
            }
        });
        dialog.show();
    }

    private void setAlarm(int minute) {
        String[] arr = getResources().getStringArray(R.array.duringType);
        if (minute % (1440) == 0) {
            selectAlarm.setText(arr[2]);
            slideAlarm.setValue((minute / 1440));
            return;
        } else if (minute % 60 == 0) {
            selectAlarm.setText(arr[1]);
            slideAlarm.setValue((minute / 60));
            return;
        }
        selectAlarm.setText(arr[0]);
        slideAlarm.setValue(minute);
    }

    private void setDateTime(boolean isDateStart, Date date) {
        if (isDateStart) {
            textDateStart.setText(Support.displayDate(date));
            textTimeStart.setText(Support.displayTime(date));
            if (!textDateEnd.isEnabled())
                textDateEnd.setText(textDateStart.getText());
        } else {
            if (isSetEndDate || !textDateEnd.getText().toString().equals(getText(R.string.no_end_date))) {
                isDateStart = !isSetEndDate;
                textDateEnd.setText(Support.displayDate(date));
            }
            textTimeEnd.setText(Support.displayTime(date));
        }
    }

    private void changeActionBarAccept(boolean attend) {
        if (attend) {
            showEditBar(true);
        } else {
            showEditBar(false);
            layoutActionDefault.setVisibility(View.GONE);
        }
    }

    private void enableEditorAccept() {
        enableEditor(true);
        textDateEnd.setEnabled(false);
        textTimeEnd.setEnabled(false);
        textDateStart.setClickable(false);
        textTimeStart.setClickable(false);
        txtSearchContact.setClickable(false);
        txtLocation.setEnabled(false);
        btnInvite.setClickable(false);
        iBtnSearch.setClickable(false);
        multiRepeat.setEnable(false);
        iBtnCancel.setClickable(false);
    }

    private void enableEditor(boolean isEnable) {
        if (isEnable)
            textAction.setText(R.string.action_edit);
        else
            textAction.setText(R.string.action_view);
        txtTaskName.setEnabled(isEnable);
        textDateEnd.setEnabled(isEnable);
        textTimeEnd.setEnabled(isEnable);
        textDateStart.setClickable(isEnable);
        textTimeStart.setClickable(isEnable);
        slideAlarm.setEnable(isEnable);
        selectAlarm.setMyEnable(isEnable);
        multiRepeat.setEnable(isEnable);
        txtLocation.setEnabled(isEnable);
        txtNote.setEnabled(isEnable);
        btnInvite.setClickable(isEnable);
        iBtnSearch.setClickable(isEnable);
        txtSearchContact.setClickable(isEnable);
        iBtnCancel.setClickable(isEnable);
    }

    private void showEditBar(boolean isShow) {
        Animation animation = AnimationUtils.loadAnimation(this, R.anim.enable_edit_bar);
        if (isShow) {
            layoutActionEdit.startAnimation(animation);
            layoutActionEdit.setVisibility(View.VISIBLE);
            layoutActionDefault.setVisibility(View.GONE);
            return;
        }
        layoutActionEdit.setVisibility(View.GONE);
        layoutActionDefault.startAnimation(animation);
        layoutActionDefault.setVisibility(View.VISIBLE);

    }

    private void updateUiFromFreeTime(Date from, int during) {
        textDateStart.setText(Support.displayDate(from));
        textTimeStart.setText(Support.displayTime(from));
        Date temp = Support.addDateTime(from, during);
        textDateEnd.setText(Support.displayDate(temp));
        textTimeEnd.setText(Support.displayTime(temp));
    }

    private void setCurrentDate() {
        Date current = Calendar.getInstance().getTime();
        textDateStart.setText(Support.displayDate(current));
        textTimeStart.setText(Support.displayTime(current));
        textDateEnd.setText(Support.displayDate(current));
        textTimeEnd.setText(Support.displayTime(current));
    }

    private void displayCurrentTask() {
        txtTaskName.setText(currentTask.getTaskName());
        textDateStart.setText(Support.displayDate(currentTask.getStart()));
        textTimeStart.setText(Support.displayTime(currentTask.getStart()));
        textTimeEnd.setText(Support.displayTime(Support.addDateTime(currentTask.getStart(), currentTask.getDuring())));
        String sEnd = Support.displayDate(currentTask.getEnd());

        if (currentTask.getRepeat().equals("")) {
            textDateEnd.setText(Support.displayDate(currentTask.getEnd()));
            //   Text.strike(textDateEnd, true);
        } else {
            //   Text.strike(textDateEnd, false);
            textDateEnd.setText(Support.displayDate(currentTask.getEnd()));
            if (textDateEnd.getText().toString().equals("1/1/2090"))
                textDateEnd.setText(R.string.no_end_date);
            else
                textDateEnd.setText(Support.displayDate(currentTask.getEnd()));
        }

        setAlarm(currentTask.getRemind());
        multiRepeat.setData(currentTask.getRepeat());
        txtLocation.setText(currentTask.getLocation().getAddress());
        txtNote.setText(currentTask.getNote().toString());
    }

    private void sendEmail(String[] address) {
        if(address == null || address.length < 1){
            return;
        }
        if (!SysApp.sendEmail(this, address))
            Toast.makeText(getBaseContext(), R.string.send_mail_error, Toast.LENGTH_LONG).show();
    }

    private void call(String phoneNumber) {
        if (!SysApp.call(this, phoneNumber))
            Toast.makeText(getBaseContext(), R.string.make_call_error, Toast.LENGTH_LONG).show();
    }

    private void viewDetailContact(Contact contact) {
        User user = contact.getUser();
        final Dialog dialog = new Dialog(this, R.style.customDialogTheme);
        dialog.setContentView(R.layout.dialog_contact);
        //  View view = LayoutInflater.from(this).inflate(R.layout.dialog_contact, null);
        RelativeLayout layoutPhone = (RelativeLayout) dialog.findViewById(R.id.rLayoutDialogContactPhone);
        RelativeLayout layoutFb = (RelativeLayout) dialog.findViewById(R.id.rLayoutDialogContactFb);
        RelativeLayout layoutSkype = (RelativeLayout) dialog.findViewById(R.id.rLayoutDialogContactSkype);
        TextView userName = (TextView) dialog.findViewById(R.id.textDialogContactName);
        final TextView email = (TextView) dialog.findViewById(R.id.textDialogContactEmail);
        final TextView phone = (TextView) dialog.findViewById(R.id.textDialogContactPhone);
        final TextView status = (TextView) dialog.findViewById(R.id.textDialogContactStatus);
        TextView facebook = (TextView) dialog.findViewById(R.id.textDialogContactFb);
        TextView skype = (TextView) dialog.findViewById(R.id.textDialogContactFb);
        ImageButton iBtnEmail = (ImageButton) dialog.findViewById(R.id.iBtnDialogEmail);
        ImageButton iBtnPhone = (ImageButton) dialog.findViewById(R.id.iBtnDialogPhone);
        ImageButton iBtnFacebook = (ImageButton) dialog.findViewById(R.id.iBtnDialogFb);
        Button btnClose = (Button) dialog.findViewById(R.id.btnCloseContactDialog);
        // init values

        userName.setText(user.getUserName());
        email.setText(user.getEmail());
        if (contact.isAttend())
            status.setText(R.string.text_ready);
        else
            status.setText(R.string.text_waiting);
        String temp = user.getPhone();
        if (temp != null && !temp.equals(""))
            phone.setText(temp);
        else
            layoutPhone.setVisibility(View.GONE);
        temp = user.getFacebook();
        if (temp != null && !temp.equals(""))
            facebook.setText(temp);
        else
            layoutFb.setVisibility(View.GONE);
        temp = user.getSkype();
        if (temp != null && !temp.equals(""))
            skype.setText(temp);
        else
            layoutSkype.setVisibility(View.GONE);
        //init action
        iBtnEmail.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();
                sendEmail(new String[]{email.getText().toString()});
            }
        });
        iBtnPhone.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();
                call(phone.getText().toString());
            }
        });
        iBtnFacebook.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();
                Toast.makeText(getBaseContext(), R.string.buding, Toast.LENGTH_SHORT).show();
            }
        });
        btnClose.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();
            }
        });
        dialog.show();
    }

    private void enableEndDate(String repeat) {
        if (repeat != null && !repeat.equals("")) {
            textDateEnd.setText(R.string.no_end_date);
            textDateEnd.setEnabled(true);
        } else {
            textDateEnd.setText(textDateStart.getText());
            textDateEnd.setEnabled(false);
        }
    }

    @Override
    public void remove(Contact contact, int pos) {
        Contact contact1 = currentTask.getListContact().get(pos);
        if (contact1.getContactId() == 0) {
            currentTask.getListContact().remove(pos);
            contactAdapter.notifyDataSetChanged();
        } else
            Toast.makeText(getBaseContext(), R.string.no_delete, Toast.LENGTH_SHORT).show();

    }

    class loadCurrentTask extends AsyncTask<String, Void, Void> {
        private int taskId;

        public loadCurrentTask(int taskId) {
            this.taskId = taskId;
        }

        @Override
        protected Void doInBackground(String... strings) {
            currentTask = taskService.task(taskId);
            currentTask.setListContact(contactService.contactsByTask(currentTask.getTaskId()));
            contactAdapter.setList(currentTask.getListContact());
            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            contactAdapter.notifyDataSetChanged();
            if(currentTask == null){
                Toast.makeText(getApplication(),R.string.event_not_found,Toast.LENGTH_SHORT).show();
                finish();
                return;
            }
            if(currentTask.getPublicId() == 0) {
                if (currentTask.isActive() == false) {
                    showDialogRestore(currentTask.getTaskId());
                } else
                    displayCurrentTask();
            }else {
                if(currentTask.getPublicId() == -1) {
                    layoutActionDefault.setVisibility(View.GONE);
                    textAction.setTextColor(getResources().getColor(R.color.text_red));
                    textAction.setText(R.string.event_canceled);
                }
                 displayCurrentTask();
            }

            if(isInvite){
                toggleAttend.setChecked(currentTask.isActive());
                changeActionBarAccept(currentTask.isActive());
                enableEditorAccept();
                textAction.setVisibility(View.GONE);
                toggleAttend.setVisibility(View.VISIBLE);
            }
        }
    }

    class loadSysContact extends AsyncTask<String, Void, Void> {
        private boolean isExtend = false;

        public loadSysContact(boolean isExtend) {
            this.isExtend = isExtend;
        }

        @Override
        protected void onPreExecute() {
            lockUI(true);
            progressBar.setVisibility(View.VISIBLE);
            if (isExtend) {
                //     layoutSearch.setVisibility(View.VISIBLE);
                listViewSysContact.setVisibility(View.VISIBLE);
                listViewContact.setVisibility(View.GONE);
            } else {
                //     layoutSearch.setVisibility(View.GONE);
                listViewSysContact.setVisibility(View.GONE);
                listViewContact.setVisibility(View.VISIBLE);
            }
        }

        @Override
        protected Void doInBackground(String... strings) {
            List<User> sysContact = ContactSupport.getContacts(AddNewActivity.this);
            for (User u : sysContact) {
                userService.checkAndCreate(u);
            }
            listUser = userService.users(true);
            if (listUser.size() > 0)
                listUser.remove(0);
            sysContactAdapter.setList(listUser);
            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            lockUI(false);
            progressBar.setVisibility(View.GONE);
            sysContactAdapter.setCurrentList(currentTask.getListContact());
            sysContactAdapter.notifyDataSetChanged();
        }
    }

    private void showPickerDialog(boolean chooseDate, final boolean isStart, final Date currentDate) {

        final Calendar calendar = Calendar.getInstance();
        final Dialog dialog = new Dialog(this);
        dialog.setContentView(R.layout.dialog_datetime_picker_new);
        final Switch btnSwitch = (Switch) dialog.findViewById(R.id.btnSwitchDateTime);
        final DatePicker datePicker = (DatePicker) dialog.findViewById(R.id.datePickerDialog);
        final TimePicker timePicker = (TimePicker) dialog.findViewById(R.id.timePickerDialog);
        Button btnClose = (Button) dialog.findViewById(R.id.btnCloseContactDialog);
        Button btnSet = (Button) dialog.findViewById(R.id.btnSetTimeDialog);
        Calendar temp = Calendar.getInstance();
        temp.setTime(currentDate);
        datePicker.updateDate(temp.get(Calendar.YEAR), temp.get(Calendar.MONTH), temp.get(Calendar.DAY_OF_MONTH));
        timePicker.setCurrentHour(currentDate.getHours());
        timePicker.setCurrentMinute(currentDate.getMinutes());

        btnSwitch.setChecked(chooseDate);
        if (chooseDate) {
            datePicker.setVisibility(View.VISIBLE);
            timePicker.setVisibility(View.GONE);
        } else {
            datePicker.setVisibility(View.GONE);
            timePicker.setVisibility(View.VISIBLE);
        }
        btnSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                if (btnSwitch.isChecked()) {
                    datePicker.setVisibility(View.VISIBLE);
                    timePicker.setVisibility(View.GONE);
                } else {
                    datePicker.setVisibility(View.GONE);
                    timePicker.setVisibility(View.VISIBLE);
                }
            }
        });

        btnSet.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                calendar.set(Calendar.YEAR, datePicker.getYear());
                calendar.set(Calendar.MONTH, datePicker.getMonth());
                calendar.set(Calendar.DAY_OF_MONTH, datePicker.getDayOfMonth());
                calendar.set(Calendar.HOUR_OF_DAY, timePicker.getCurrentHour());
                calendar.set(Calendar.MINUTE, timePicker.getCurrentMinute());
                setDateTime(isStart, calendar.getTime());
                dialog.dismiss();
            }
        });
        btnClose.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();
            }
        });
        dialog.show();
    }

    private void showDialogMessage() {
        final Dialog dialog = new Dialog(this);
        dialog.setOnCancelListener(this);
        View view = LayoutInflater.from(this).inflate(R.layout.dialog_message, null);
        dialog.setContentView(view);
        Button btnOk = (Button) view.findViewById(R.id.btnAcceptMessageDialog);
        final EditText txtMessage = (EditText) view.findViewById(R.id.txtMessageDialog);
        btnOk.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();
                message = txtMessage.getText().toString();
                loadSaveTask = new saveTask();
                loadSaveTask.execute();
            }
        });
        dialog.show();
    }

    private void showDialogFindUser(final List<User> list) {
        final Dialog dialog = new Dialog(this);
        dialog.setOnCancelListener(this);
        View view = LayoutInflater.from(this).inflate(R.layout.dialog_find_user, null);
        dialog.setContentView(view);
        ListView listView = (ListView) view.findViewById(R.id.listViewFindUser);
        Button btnCancel = (Button) view.findViewById(R.id.btnCancelFindUserDialog);
        FindUserAdapter adapter = new FindUserAdapter(this, list);
        listView.setAdapter(adapter);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                boolean isExit = false;
                User checkUser = list.get(i);
                for (Contact contact : currentTask.getListContact()) {
                    String email = contact.getUser().getEmail();
                    if (email.equals(checkUser.getEmail())) {
                        isExit = true;
                        break;
                    }
                }
                if (!isExit) {
                    userService.checkAndCreate(checkUser);
                    Contact contact = new Contact();
                    contact.setTask(currentTask);
                    contact.setLeader(false);
                    contact.setAttend(false);
                    contact.setActive(true);
                    contact.setUser(userService.user(checkUser.getEmail()));
                    currentTask.getListContact().add(contact);
                    contactAdapter.notifyDataSetChanged();
                    dialog.dismiss();
                } else
                    Toast.makeText(getBaseContext(), getText(R.string.user_exit), Toast.LENGTH_SHORT).show();
                Toast.makeText(getBaseContext(), R.string.add_invite_success, Toast.LENGTH_SHORT).show();
            }
        });
        btnCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();
            }
        });
        //   new loadSysContact(true).execute();
        dialog.show();
    }
    private void showDialogRestore(final int taskId) {
        final Dialog dialog = new Dialog(this);
        dialog.setOnCancelListener(this);
        View view = LayoutInflater.from(this).inflate(R.layout.dialog_restore, null);
        dialog.setContentView(view);
        Button btnOk = (Button) view.findViewById(R.id.btnOkConfirmDialog);
        Button btnCancel = (Button) view.findViewById(R.id.btnCancelConfirmDialog);

        btnOk.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                taskService.active(taskId, true);
                new loadCurrentTask(taskId).execute();
                dialog.dismiss();
            }
        });
        btnCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();
                finish();
            }
        });
        dialog.show();
    }
    private void showDialogConflict(List<Clash> list) {
        final Dialog dialog = new Dialog(this);
        dialog.setOnCancelListener(this);
        View view = LayoutInflater.from(this).inflate(R.layout.dialog_conflict, null);
        dialog.setContentView(view);
        Button btnOk = (Button) view.findViewById(R.id.btnOkConflictDialog);
        Button btnCancel = (Button) view.findViewById(R.id.btnCancelConflictDialog);
        ListView listView = (ListView) view.findViewById(R.id.listViewConflict);
        ConflictAdapter adapter = new ConflictAdapter(this, list);
        listView.setAdapter(adapter);
        btnOk.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                loadSaveTask.setContinue(true);
                dialog.dismiss();
            }
        });
        btnCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                loadSaveTask.setWait(false);
                dialog.dismiss();
            }
        });
        dialog.show();
    }

    class FindUser extends AsyncTask<Void, Void, Void> {
        private List<User> result;
        private String key;

        public FindUser(String key) {
            this.key = key;
        }

        @Override
        protected Void doInBackground(Void... voids) {
            result = JSONParser.findUser(key);
            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            lockUI(false);
            progressBar.setVisibility(View.GONE);
            if (result.size() == 0)
                Toast.makeText(getBaseContext(), getText(R.string.not_result), Toast.LENGTH_SHORT).show();
            else
                showDialogFindUser(result);
        }

        @Override
        protected void onPreExecute() {
            lockUI(true);
            progressBar.setVisibility(View.VISIBLE);
        }
    }

    class saveTask extends AsyncTask<Void, Void, String> {
        private final String ERROR = "0";
        private final String SUCCESS = "1";
        private boolean isWait = true;
        private boolean isContinue = true;

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            lockUI(true);
            progressBar.setVisibility(View.VISIBLE);
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            if (s != null)
                if (s.equals(SUCCESS)) {
                    LogSupport.saveLog(AddNewActivity.this, taskService.getAlarm(Calendar.getInstance().getTime()));
                    if (isInvite == false)
                        finish();
                }
            lockUI(false);
            progressBar.setVisibility(View.GONE);
        }

        public void setWait(boolean isWait) {
            this.isWait = isWait;
        }

        public void setContinue(boolean isContinue) {
            this.isContinue = isContinue;
        }

        @Override
        protected String doInBackground(Void... voids) {
            getValues();

            final List<Clash> clashs = taskService.getClash(currentTask);
            if (clashs.size() > 0) {
                isContinue = false;
                AddNewActivity.this.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        progressBar.setVisibility(View.GONE);
                        showDialogConflict(clashs);
                    }
                });
            }
            while (isWait) {
                if (isContinue == false)
                    continue;
                AddNewActivity.this.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        progressBar.setVisibility(View.VISIBLE);
                    }
                });
                isWait = false;
                if (isCreate == false) {
                    taskService.update(currentTask);
                } else {
                    taskService.create(currentTask);
                    currentTask.setTaskId(taskService.newId());
                    currentTask.getListContact().add(getContactMe());
                }
                createContact(isInvite);
                if (isCreate)
                    crateTrack(Track.ACTION_SEND_INVITE, message);  // update message here
                else {
                    if (isInvite) {
                        if (!isUpdateInfoInvite)
                            crateTrack(Track.ACTION_SEND_ACCEPT, userService.getMe().getEmail());  // update message here
                    }
                    else
                        crateTrack(Track.ACTION_UPDATE_INVITE, message);  // update message here
                }
                return SUCCESS;
            }
            return null;
        }
    }

    private void getValues() {
        currentTask.setTaskName(txtTaskName.getText().toString());
        Date start = Support.toDateTime(textDateStart.getText().toString() + " " + textTimeStart.getText(), true);
        Date end;
        if (textDateEnd.getText().toString().equals(getText(R.string.no_end_date))) {
            end = Support.toDateTime(sLastDate + " " + textTimeEnd.getText().toString(), true);
        } else
            end = Support.toDateTime(textDateEnd.getText().toString() + " " + textTimeEnd.getText(), true);
        currentTask.setStart(start);
        currentTask.setEnd(end);
        currentTask.setDuring(getDuring(start, end));
        currentTask.setRepeat(multiRepeat.getData());
        currentTask.setRemind(getAlarm(slideAlarm.getValue(), selectAlarm.getText()));
        currentTask.setCategory(new Category(1));
        currentTask.setLocation(locationService.crateOrUpdate(txtLocation.getText().toString()));
        currentTask.setNote(txtNote.getText().toString());
        currentTask.setActive(true);
    }

    private void createContact(boolean isInvite) {
        if (isInvite)
            return;
        for (Contact contact : currentTask.getListContact()) {
            if (contact.getContactId() == 0) {
                contact.setTask(currentTask);
                contactService.create(contact);
            }
        }
    }

    private void findUser() {
        if (txtSearchContact.getText().toString().equals("")) {
            Animation animation = AnimationUtils.loadAnimation(getApplication(), R.anim.vibrate);
            txtSearchContact.startAnimation(animation);
            Toast.makeText(getBaseContext(), getText(R.string.txt_search_null), Toast.LENGTH_SHORT).show();
            return;
        }
        if (!Network.isConnect(this)) {
            Toast.makeText(getBaseContext(), getText(R.string.not_connect), Toast.LENGTH_SHORT).show();
            return;
        }
        new FindUser(txtSearchContact.getText().toString()).execute();
    }

    private void crateTrack(String action, String message) {
        //      Log.d("add new zize",currentTask.getListContact().size()+"");
        if (currentTask.getListContact().size() > 1) {
            saveTrack(currentTask, action, message);
        }
    }

    private void saveTrack(Task task, String action, String message) {
        TrackService trackService = TrackDao.getInstance(this);
        Track track = new Track();
        track.setTask(task);
        track.setLastTime(Support.toDateTime("1111-11-11 11:11:00", false));
        track.setActon(action);
        track.setMessage(message);
        track.setCommit(false);
        track.setActive(true);
        trackService.create(track);
    }

    private int getDuring(Date start, Date end) {

        Date temp = new Date();
        temp.setDate(start.getDate());
        temp.setMonth(start.getMonth());
        temp.setYear(start.getYear());
        temp.setHours(end.getHours());
        temp.setMinutes(end.getMinutes());
        return (int) ((temp.getTime() - start.getTime()) / (1000 * 60));
    }

    private int getAlarm(int value, String type) {
        String[] arr = getResources().getStringArray(R.array.duringType);
        if (type.equals(arr[2]))
            return 1440 * value;
        if (type.equals(arr[1]))
            return 60 * value;
        return value;

    }

    private void lockUI(boolean isLock) {
        if (isLock)
            this.getWindow().addFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);
        else
            this.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);
    }

    private Date getDateFromView(boolean isStart) {
        String sDate;
        if (isStart)
            sDate = textDateStart.getText() + " " + textTimeStart.getText().toString();
        else {
            if (textDateEnd.getText().toString().equals(getText(R.string.no_end_date)))
                sDate = textDateStart.getText() + " " + textTimeEnd.getText().toString();
            else
                sDate = textDateEnd.getText() + " " + textTimeEnd.getText().toString();
        }
        return Support.toDateTime(sDate, true);
    }

    private void saveTask() {
        Animation animation = AnimationUtils.loadAnimation(getApplication(), R.anim.vibrate);
        if (txtTaskName.getText().toString().equals("")) {
            txtTaskName.startAnimation(animation);
            return;
        }
        Date start = getDateFromView(true);
        Date end = getDateFromView(false);
        if(end.getTime() - start.getTime() < 60000 && !textDateEnd.getText().equals(getText(R.string.no_end_date))) { // 1000*60*60
            textDateEnd.startAnimation(animation);
            textTimeEnd.startAnimation(animation);
            return;
        }else
            if(Support.validateTime(start,end) == false){
                textTimeEnd.startAnimation(animation);
                return;
            }
        if (currentTask.getListContact().size() > 0 && isCreate && isInvite == false)
            showDialogMessage();
        else {
            loadSaveTask = new saveTask();
            loadSaveTask.execute();
        }
    }
    private void sendMailAll(){
        if(currentTask == null)
            return;
        int numOfPeople = currentTask.getListContact().size();
        boolean exitMe = false;
        String myEmail = userService.getMe().getEmail();
        User user;
        StringBuilder address = new StringBuilder();
        for(int i = 0;i < numOfPeople; i++){
            user = currentTask.getListContact().get(i).getUser();
            if(!myEmail.equals(user.getEmail())){
                if(i == numOfPeople - 1 )
                    address.append(user.getEmail());
                else
                    address.append(user.getEmail()+",");
            }else
                exitMe = true;
        }
        if( (exitMe && numOfPeople > 1) || ( !exitMe && numOfPeople > 0) ) {
            if (!SysApp.sendEmail(this, address.toString().split(",")))
                Toast.makeText(getBaseContext(), R.string.send_mail_error, Toast.LENGTH_LONG).show();
        }else
            Toast.makeText(getBaseContext(),R.string.no_contact, Toast.LENGTH_LONG).show();
    }
    @Override
    public void onCancel(DialogInterface dialogInterface) {
        loadSaveTask.setWait(false);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iBtnInviteAddNew:
                new loadSysContact(btnInvite.isChecked()).execute();
                break;
            case R.id.iBtnSaveAddNew:
                isUpdateInfoInvite = true;
                saveTask();
                break;
            case R.id.iBtnSearchUser:
                findUser();
                break;
            case R.id.iBtnBackAđNew:
                finish();
                break;
            case R.id.iBtnCancelAddNew:
                if (currentTask.getTaskId() != 0) {
                    displayCurrentTask();
                    showEditBar(false);
                    enableEditor(false);
                }
                break;
            case R.id.iBtnDeleteAddNew:
                if (currentTask.getTaskId() == 0)
                    Toast.makeText(getBaseContext(), R.string.nothing_delete, Toast.LENGTH_SHORT).show();
                deleteTask(currentTask.getTaskId());
                break;
            case R.id.iBtnEditAddNew:
                showEditBar(true);
                enableEditor(true);
                break;
            case R.id.textStartAddNew:
                showPickerDialog(true, true, getDateFromView(true));
                break;
            case R.id.textStartTimeAddNew:
                showPickerDialog(false, true, getDateFromView(true));
                break;
            case R.id.textEndAddNew:
                if (!multiRepeat.getData().equals("")) {
                    isSetEndDate = true;
                    showPickerDialog(true, false, getDateFromView(false));
                }
                break;
            case R.id.textEndTimeAddNew:
                showPickerDialog(false, false, getDateFromView(false));
                break;
            case R.id.iBtnSendMail:
                sendMailAll();
                break;
            case R.id.toggleAttendAddNew:
                isUpdateInfoInvite = false;
                if (toggleAttend.isChecked()) { // attend
                    saveTask();
                    contactService.attend(currentTask.getTaskId(), userService.getMe().getUserId(), true);
                    changeActionBarAccept(true);
                } else {
                    taskService.active(currentTask.getTaskId(), false);
                    contactService.attend(currentTask.getTaskId(), userService.getMe().getUserId(), false);
                    layoutActionEdit.setVisibility(View.GONE);
                }
                break;
        }
    }

    private AdapterView.OnItemClickListener contactClick = new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
            viewDetailContact(currentTask.getListContact().get(i));
        }
    };

    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int pos, long l) {
        ImageView status = (ImageView) view.findViewById(R.id.imageViewSysContactStatus);

        if (status.getVisibility() == View.VISIBLE) {
            for (int i = 0; i < currentTask.getListContact().size(); i++) {
                Contact contact = currentTask.getListContact().get(i);
                // User user = currentTask.getListContact().get(i).getUser();
                if (contact.getUser().getEmail().equals(listUser.get(pos).getEmail())) {
                    if (contact.getContactId() != 0) {
                        Toast.makeText(getBaseContext(), R.string.no_delete, Toast.LENGTH_SHORT).show();
                        return;
                    }
                    currentTask.getListContact().remove(i);
                    contactAdapter.notifyDataSetChanged();
                    sysContactAdapter.notifyDataSetChanged();
                    return;
                }
            }
            return;
        }
        Contact contact = new Contact();
        contact.setTask(currentTask);
        contact.setLeader(false);
        contact.setAttend(false);
        contact.setActive(true);
        contact.setUser(listUser.get(pos));
        currentTask.getListContact().add(contact);
        contactAdapter.notifyDataSetChanged();
        sysContactAdapter.notifyDataSetChanged();
    }

    @Override
    public void beforeTextChanged(CharSequence charSequence, int i, int i2, int i3) {

    }

    @Override
    public void onTextChanged(CharSequence charSequence, int i, int i2, int i3) {
        if (sysContactAdapter == null)
            return;
        List<User> result = new ArrayList<User>();
        String name, email;
        for (User item : listUser) {
            name = item.getUserName();
            email = item.getEmail();
            if (item.getUserName().contains(charSequence))
                result.add(item);
        }
        sysContactAdapter.setList(result);
        sysContactAdapter.notifyDataSetChanged();
    }

    @Override
    public void select(String repeat) {
        enableEndDate(repeat);
    }

    @Override
    public void afterTextChanged(Editable editable) {

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        loadSaveTask.setWait(false);
    }
}
